﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Core.Models;
using Web.Core.Security;
using Ayatta.Contract.Domain;
using Ayatta.Contract.Extension;
using Ayatta.Common.Extension;

namespace Web.Cart.Controllers
{
    public class CartController : BaseController
    {
        public CartController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        /// <summary>
        /// 查看购物车
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(ShoppingCart cart, ShoppingCartOperate opt = ShoppingCartOperate.UpdateQuantity, int itemId = 0, int skuId = 0, int? quantity = 0)
        {
            if (Request.IsAjaxRequest())
            {
                switch (opt)
                {
                    case ShoppingCartOperate.Remove:
                        if (itemId > 0 && skuId >= 0)
                        {
                            cart.Remove(itemId, skuId);
                        }
                        break;
                    case ShoppingCartOperate.Clear:
                        Session[ShoppingCart.SessionKey] = null;
                        break;
                    default:
                        if (itemId > 0 && skuId >= 0 && quantity.HasValue)
                        {
                            cart.UpdateQuantity(itemId, skuId, quantity.Value);
                        }
                        break;
                }
            }
            ProcessDiscount(cart);
            return PartialView(cart);
        }

        /// <summary>
        /// 添加到购物车
        /// </summary>
        /// <param name="param">商品Id </param>
        /// <param name="skuId">skuId </param>
        /// <param name="qty">数量 </param>
        /// <param name="callback">CallBack</param>
        /// <param name="cart">ShoppingCart</param>
        /// <returns></returns>
        public ActionResult Add(int? param, int? skuId, string callback, ShoppingCart cart, int qty = 1)
        {
            var result = new MagicKit<object>();

            if (!param.HasValue || !skuId.HasValue || qty < 1 || string.IsNullOrEmpty(callback))
            {
                result.Message = "请检查参数";
                return Jsonp(result, callback);
            }
            //var shoppingCartConfig = InfrastructureApi.GetSystemConfig().ShoppinCartConfig;
            var anonymousBuyEnabled = true; //shoppingCartConfig.AnonymousBuyEnabled;

            if (!anonymousBuyEnabled && !Request.IsAuthenticated)
            {
                result.Message = "请先登录";
                return Jsonp(result, callback);
            }
           

            var item = Store.Value.ProductItemGet(param.Value);
            if (item != null)
            {
                var cartItem = new ShoppingCartItem();
                cartItem.Picture = item.Picture(ProductItemImageSize.S);
                if (!item.ProductItemSkus.IsNullOrEmpty())
                {
                    var sku = item.ProductItemSkus.FirstOrDefault(o => o.Id == skuId.Value);
                    if (sku != null)
                    {
                        cartItem.SkuId = skuId.Value;
                        cartItem.Price = sku.Price;
                        cartItem.Stock = sku.Quantity;
                        cartItem.PropTexts = sku.PropTexts;
                        var propImgs = item.PropImgs();
                        var skuProps = sku.SkuProps;
                        foreach (var skuProp in skuProps)
                        {
                            var s = skuProp.PId + ":" + skuProp.VId;
                            foreach (var propImg in propImgs)
                            {
                                if (propImg.First == s)
                                {
                                    cartItem.Picture = propImg.Third;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    cartItem.SkuId = 0;
                    cartItem.Price = item.Price;
                    cartItem.Stock = item.Quantity;
                    cartItem.PropTexts = null;
                }
                cartItem.Id = item.Id;
                cartItem.Name = item.Name;
                cartItem.Quantity = qty;
                cartItem.OrderMaxQuantity = 4;
                cartItem.IsVirtual = item.IsVirtual;
                
                cart.Add(cartItem);

            }
            ProcessDiscount(cart);

            result.Status = true;
            result.Data = cart.ToMiniCart();
            result.Message = string.Empty;
            return Jsonp(result, callback);
        }

        public ActionResult Remove(int? param, int skuId, string callback, ShoppingCart cart)
        {
            var result = new MagicKit<ShoppingCart>();
            if (param.HasValue && param.Value > 0 && skuId >= 0)
            {
                cart.Remove(param.Value, skuId);
            }
            return Jsonp(result, callback);
        }

        public ActionResult Clear(string callback)
        {
            Session[ShoppingCart.SessionKey] = null;
            var result = new MagicKit<string>(true, string.Empty);
            return Jsonp(result, callback);
        }

        public ActionResult Mini(string callback, ShoppingCart cart)
        {
            var miniCart = cart.ToMiniCart();
            var result = new MagicKit<MiniCart>(true, miniCart);
            return Jsonp(result, callback);
        }

        [HttpPost]
        public ActionResult Address(int param = 0)
        {
            var userId = User.Identity.Identity().Id;
            UserAddress model = null;
            if (param > 0)
            {
                model = Passport.Value.UserAddressGet(param, userId);
            }
            return PartialView(model);
        }
    }
}
